/**
 * token认证的中间件
 */
import jwt from 'jsonwebtoken'
import { SECRET } from '#src/controllers/userController/index.js'

// 路由白名单，否则登录接口也会验证token
let whiteList = ['/api/user/login', '/api/user/register']

export default (req, res, next) => {
  let url = req.path

  if (whiteList.includes(url)) {
    // 直接放行
    next()

    return
  }

  let authorization = req.headers.authorization

  // 从token里面拿到用户id

  if (!authorization) {
    res.json({
      code: 1030,
      data: null,
      message: '未授权'
    })
    // 没有验证通过，就不要执行next
    return
  }

  let token = authorization.split(' ')[1]

  try {
    let decoded = jwt.verify(token, SECRET)

    // 将用户信息挂载到req全局对象上
    req.userId = decoded.id

    // console.log('decoded 包含2个内容，一个是用户id， 一个是iat', decoded);

    next()
  } catch (error) {
    console.log(error)
    res.json({
      code: -1,
      data: null,
      message: 'token错误'
    })
  }
}
